<script setup lang="ts">
import {ref, onBeforeMount, onMounted} from 'vue'
import {server} from '@/config/index'
import definePeerStore from '@/stores/peer'
import MonitorCard from '@/components/MonitorCard.vue'
import {WebSocket} from "vite";
import ReconnectingWebSocket from 'reconnecting-websocket';
import Peer from "peerjs";
const MonitorList = ref([1, 2, 3, 4, 5, 6])
// import {server} from '@/config/index'

const peerStore=definePeerStore()
// const peerId=ref('')
onBeforeMount(()=>{

})
const installPeer=()=>{
  return new Promise(resolve => {
    console.log('start connect peerjs');
    const {host, port, path} = server.peerServer
    const localPeer = new Peer({host, port, path});
    localPeer.on("open", localPeerId => {
      console.log("localPeer opened,the local peer id is: ", localPeerId);
      // peerStore.localPeer = localPeer;
      // peerId.value=localPeerId
      resolve(localPeerId)
    });
  })

}
const conn=ref<any>(null)
const installSocket=(peerId:string)=>{
  return new Promise((resolve)=>{
    const {host, port, path} = server.webSocketServer;

    // const url=`ws://${host}:${port}${path}/${peerId}/${'徐辰曦'}`;
    const url=`ws://${host}:${port}${path}/${peerId}?nickname=xcx`;
    console.log(url)
    const connection=new ReconnectingWebSocket(url)
    // const connection=new WebSocket(url,['xcx']);
    connection.onmessage = event => {
      let message = JSON.parse(event.data);
      console.log("webSocketConnection.onmessage:", message);
    };

    connection.onclose = event => {
      console.log("webSocketConnection.onclose:", event);

    };

    connection.onerror = event => {
      console.log("webSocketConnection.onerror:", event);

    };

    connection.onopen = event => {
      console.log("webSocketConnection.onopen:", event);
    };
    conn.value=connection
    resolve(connection)

  })
}
onMounted(()=>{

})
const connectSocket=()=>{
  installPeer().then((peerId:any)=>{
    installSocket(peerId).then((conn:any)=>{
      conn.send(`
      {
        type:1,
        nickname:'xcx',
        message:'这是一个个人信息传入请求'
      }
      `)
    })
  })
  // conn.value.send({
  //   type:1,
  //   nickname:'xcx',
  //   message:'这是一个个人信息传入请求'
  // })
}
const sendMessage=()=>{
  conn.value.send(`{
    type:1,
    nickname:'xcx',
    message:'这是一个个人信息传入请求'
  }`)
}
</script>

<template>
  <!-- <router-link to="/monitor">monitor</router-link> -->
<!--  <div class="flex-wrap-list">-->
<!--    <MonitorCard v-for="item in MonitorList" />-->
<!--  </div>-->
  <button @click="connectSocket">click</button>
  <button @click="sendMessage">click</button>
</template>
<style scoped>
.flex-wrap-list{
   width: 100%;
   display: flex;
   justify-content: space-around;
   flex-wrap: wrap;
}
</style>